<!DOCTYPE html><html lang="zh-Hans"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><meta name="description" content="vue路由"><meta name="keywords" content="vue less route"><meta name="author" content="晟松"><meta name="copyright" content="晟松"><title>vue路由 | 晟松</title><link rel="shortcut icon" href="/logo.png"><link rel="stylesheet" href="/css/index.css?version=1.9.0"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@latest/css/font-awesome.min.css?version=1.9.0"><meta name="format-detection" content="telephone=no"><meta http-equiv="x-dns-prefetch-control" content="on"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><link rel="dns-prefetch" href="https://hm.baidu.com"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?c34d81d53341febe06a155941e2df16d";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();</script><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容:${query}"}},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  hexoVersion: '5.4.0'
} </script><meta name="generator" content="Hexo 5.4.0"></head><body><i class="fa fa-arrow-right" id="toggle-sidebar" aria-hidden="true"></i><div id="sidebar" data-display="true"><div class="toggle-sidebar-info text-center"><span data-toggle="切换文章详情">切换站点概览</span><hr></div><div class="sidebar-toc"><div class="sidebar-toc__title">目录</div><div class="sidebar-toc__progress"><span class="progress-notice">你已经读了</span><span class="progress-num">0</span><span class="progress-percentage">%</span><div class="sidebar-toc__progress-bar"></div></div><div class="sidebar-toc__content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#router%E8%B7%AF%E7%94%B1"><span class="toc-number">1.</span> <span class="toc-text">router路由</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8A%A8%E6%80%81%E8%B7%AF%E7%94%B1"><span class="toc-number">1.1.</span> <span class="toc-text">动态路由</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%B5%8C%E5%A5%97%E8%B7%AF%E7%94%B1"><span class="toc-number">1.2.</span> <span class="toc-text">嵌套路由</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%BC%96%E7%A8%8B%E5%BC%8F%E5%AF%BC%E8%88%AA"><span class="toc-number">1.3.</span> <span class="toc-text">编程式导航</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%91%BD%E5%90%8D%E8%B7%AF%E7%94%B1"><span class="toc-number">1.4.</span> <span class="toc-text">命名路由</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%87%8D%E5%AE%9A%E5%90%91%E5%92%8C%E5%88%AB%E5%90%8D"><span class="toc-number">1.5.</span> <span class="toc-text">重定向和别名</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%B7%AF%E7%94%B1%E7%BB%84%E4%BB%B6%E4%BC%A0%E5%8F%82"><span class="toc-number">1.6.</span> <span class="toc-text">路由组件传参</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%B7%AF%E7%94%B1%E5%AE%88%E5%8D%AB"><span class="toc-number">1.7.</span> <span class="toc-text">路由守卫</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AE%8C%E6%95%B4%E7%9A%84%E5%AF%BC%E8%88%AA%E8%A7%A3%E6%9E%90%E6%B5%81%E7%A8%8B"><span class="toc-number">1.8.</span> <span class="toc-text">完整的导航解析流程</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%85%B6%E4%BB%96"><span class="toc-number">1.9.</span> <span class="toc-text">其他</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E8%B7%AF%E7%94%B1%E5%85%83%E4%BF%A1%E6%81%AF"><span class="toc-number">1.9.1.</span> <span class="toc-text">路由元信息</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E8%BF%87%E6%B8%A1%E5%8A%A8%E6%95%88"><span class="toc-number">1.9.2.</span> <span class="toc-text">过渡动效</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%95%B0%E6%8D%AE%E8%8E%B7%E5%8F%96"><span class="toc-number">1.9.3.</span> <span class="toc-text">数据获取</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%BB%9A%E5%8A%A8%E8%A1%8C%E4%B8%BA"><span class="toc-number">1.9.4.</span> <span class="toc-text">滚动行为</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E8%B7%AF%E7%94%B1%E6%87%92%E5%8A%A0%E8%BD%BD"><span class="toc-number">1.9.5.</span> <span class="toc-text">路由懒加载</span></a></li></ol></li></ol></li></ol></div></div><div class="author-info hide"><div class="author-info__avatar text-center"><img src="/img/avatar.png"></div><div class="author-info__name text-center">晟松</div><div class="author-info__description text-center">晟松的博客</div><div class="follow-button"><a target="_blank" rel="noopener" href="https://gitee.com/cheng_song">Gitee</a></div><hr><div class="author-info-articles"><a class="author-info-articles__archives article-meta" href="/archives"><span class="pull-left">文章</span><span class="pull-right">52</span></a><a class="author-info-articles__tags article-meta" href="/tags"><span class="pull-left">标签</span><span class="pull-right">45</span></a></div></div></div><div id="content-outer"><div id="top-container" style="background-image: url(/img/blog-bg.jpg)"><div id="page-header"><span class="pull-left"> <a id="site-name" href="/">晟松</a></span><i class="fa fa-bars toggle-menu pull-right" aria-hidden="true"></i><span class="pull-right menus">   <a class="site-page" href="/">Home</a><a class="site-page" href="/archives">Archives</a><a class="site-page" href="/tags">Tags</a><a class="site-page" href="/categories">Categories</a></span><span class="pull-right"><a class="site-page social-icon search"><i class="fa fa-search"></i><span> 搜索</span></a></span></div><div id="post-info"><div id="post-title">vue路由</div><div id="post-meta"><time class="post-meta__date"><i class="fa fa-calendar" aria-hidden="true"></i> 2020-07-15</time><div class="post-meta-wordcount"><span>字数总计: </span><span class="word-count">3k</span><span class="post-meta__separator">|</span><span>阅读时长: 11 分钟</span></div></div></div></div><div class="layout" id="content-inner"><article id="post"><div class="article-container" id="post-content"><p><strong>B站老陈</strong></p>
<p>前面都没啥用，router路由才是核心</p>
<h3 id="router路由"><a href="#router路由" class="headerlink" title="router路由"></a>router路由</h3><p>根据不同的路径显示不同的页面。在router里面的index.js里面配置不同的路径显示的不同的组件或者页面。</p>
<p>根据选择的<router-link to ='/foo'>替换<router-view>标签来显示内容。在本质上还是一个页面。</p>
<p>所有的核心配置都在index.js里面</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">const</span> routes = [</span><br><span class="line">  &#123;</span><br><span class="line">    <span class="attr">path</span>: <span class="string">&#x27;/&#x27;</span>,</span><br><span class="line">    <span class="attr">name</span>: <span class="string">&#x27;home&#x27;</span>,</span><br><span class="line">    <span class="comment">//component: Home</span></span><br><span class="line">    <span class="attr">components</span>:&#123;</span><br><span class="line">      <span class="attr">nav</span>:navView,</span><br><span class="line">      <span class="attr">aside</span>:asideView,</span><br><span class="line">      <span class="attr">default</span>:Home</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  &#123;</span><br><span class="line">    <span class="attr">path</span>:<span class="string">&quot;/a&quot;</span>,</span><br><span class="line">    <span class="comment">//redirect:&quot;/about&quot;</span></span><br><span class="line">    <span class="attr">redirect</span>:<span class="function">(<span class="params">to</span>)=&gt;</span>&#123;</span><br><span class="line">      <span class="built_in">console</span>.log(to)</span><br><span class="line">      <span class="keyword">if</span>(to.query.go==<span class="string">&#x27;about&#x27;</span>)&#123;</span><br><span class="line">        <span class="keyword">return</span> &#123;<span class="attr">name</span>:<span class="string">&quot;about&quot;</span>&#125;</span><br><span class="line">      &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> &#123;<span class="attr">name</span>:<span class="string">&quot;news&quot;</span>,<span class="attr">params</span>:&#123;<span class="attr">id</span>:<span class="number">456789</span>&#125;&#125;</span><br><span class="line">      &#125;</span><br><span class="line">      </span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,]</span><br></pre></td></tr></table></figure>

<p>通过path，name，component设置。</p>
<p>我们可以在任何组件内通过 <code>this.$router</code> 访问路由器，也可以通过 <code>this.$route</code> 访问当前路由</p>
<h4 id="动态路由"><a href="#动态路由" class="headerlink" title="动态路由"></a><strong>动态路由</strong></h4><p>把某种模式匹配到的所有路由，全都映射到同个组件。在path里面可使用通配符 <code>*</code>进行匹配任意路径，一般用于404页面。当使用一个通配符时，<code>$route.params</code> 内会自动添加一个名为 <code>pathMatch</code> 参数，它包含了 URL 通过通配符被匹配的部分。当使用<em>通配符</em>路由时，请确保路由的顺序是正确的，也就是说含有<em>通配符</em>的路由应该放在最后。</p>
<p>有时候，同一个路径可以匹配多个路由，此时，匹配的优先级就按照路由的定义顺序：谁先定义的，谁的优先级就最高。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">routes: [</span><br><span class="line"><span class="comment">// 动态路径参数 以冒号开头</span></span><br><span class="line">&#123; <span class="attr">path</span>: <span class="string">&#x27;/user/:id&#x27;</span>, <span class="attr">component</span>: User &#125;</span><br><span class="line">]</span><br><span class="line"><span class="comment">//通过$route.params.id可获得路径后的id参数值</span></span><br><span class="line"><span class="keyword">const</span> User = &#123;</span><br><span class="line"><span class="attr">template</span>: <span class="string">&#x27;&lt;div&gt;User &#123;&#123; $route.params.id &#125;&#125;&lt;/div&gt;&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line">&#123;</span><br><span class="line"><span class="comment">// 会匹配以 `/user-` 开头的任意路径</span></span><br><span class="line"><span class="attr">path</span>: <span class="string">&#x27;/user-*&#x27;</span></span><br><span class="line">&#125;	</span><br></pre></td></tr></table></figure>

<p>可使用watch进行监听路由发生的变化</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">watch: &#123;</span><br><span class="line">    $route(to, <span class="keyword">from</span>) &#123;</span><br><span class="line">      <span class="comment">// 对路由变化作出响应...</span></span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h4 id="嵌套路由"><a href="#嵌套路由" class="headerlink" title="嵌套路由"></a><strong>嵌套路由</strong></h4><figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> VueRouter(&#123;</span><br><span class="line">  <span class="attr">routes</span>: [</span><br><span class="line">    &#123; <span class="attr">path</span>: <span class="string">&#x27;/user/:id&#x27;</span>, <span class="attr">component</span>: User,</span><br><span class="line">      <span class="attr">children</span>: [</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="comment">// 当 /user/:id/profile 匹配成功，</span></span><br><span class="line">          <span class="comment">// UserProfile 会被渲染在 User 的 &lt;router-view&gt; 中</span></span><br><span class="line">          <span class="attr">path</span>: <span class="string">&#x27;profile&#x27;</span>,</span><br><span class="line">          <span class="attr">component</span>: UserProfile</span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="comment">// 当 /user/:id/posts 匹配成功</span></span><br><span class="line">          <span class="comment">// UserPosts 会被渲染在 User 的 &lt;router-view&gt; 中</span></span><br><span class="line">          <span class="attr">path</span>: <span class="string">&#x27;posts&#x27;</span>,</span><br><span class="line">          <span class="attr">component</span>: UserPosts</span><br><span class="line">        &#125;</span><br><span class="line">      ]</span><br><span class="line">    &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">//此时，基于上面的配置，当你访问 /user/foo 时，User 的出口是不会渲染任何东西，这是因为没有匹配到合适的子路由。如果你想要渲染点什么，可以提供一个 空的 子路由</span></span><br><span class="line">&#123; <span class="attr">path</span>: <span class="string">&#x27;&#x27;</span>, <span class="attr">component</span>: UserHome &#125;</span><br></pre></td></tr></table></figure>

<p>使用children属性进行嵌套的配置。还可以继续进行嵌套。</p>
<p><strong>要注意，以 <code>/</code> 开头的嵌套路径会被当作根路径。 这让你充分的使用嵌套组件而无须设置嵌套的路径</strong></p>
<h4 id="编程式导航"><a href="#编程式导航" class="headerlink" title="编程式导航"></a><strong>编程式导航</strong></h4><p>(使用点击事件在js的mehtods里面使用)。除了使用 <code>&lt;router-link to=&quot;...&quot;&gt;</code>，<br>还可使用<code>router.push(location, onComplete?, onAbort?)</code>进行导航。</p>
<p>使用 <code>router.push</code> 方法。这个方法会向 history 栈添加一个新的记录，所以，当用户点击浏览器后退按钮时，则回到之前的 URL。</p>
<p>注意使用时的参数需要匹配：<strong>name params</strong>         <strong>path query</strong></p>
<p><strong>注意：在 Vue 实例内部，你可以通过 <code>$router</code> 访问路由实例。因此你可以调用 <code>this.$router.push</code></strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 字符串</span></span><br><span class="line">router.push(<span class="string">&#x27;home&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 对象</span></span><br><span class="line">router.push(&#123; <span class="attr">path</span>: <span class="string">&#x27;home&#x27;</span> &#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 命名路由</span></span><br><span class="line">router.push(&#123; <span class="attr">name</span>: <span class="string">&#x27;user&#x27;</span>, <span class="attr">params</span>: &#123; <span class="attr">userId</span>: <span class="string">&#x27;123&#x27;</span> &#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 带查询参数，变成 /register?plan=private</span></span><br><span class="line">router.push(&#123; <span class="attr">path</span>: <span class="string">&#x27;register&#x27;</span>, <span class="attr">query</span>: &#123; <span class="attr">plan</span>: <span class="string">&#x27;private&#x27;</span> &#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> userId = <span class="string">&#x27;123&#x27;</span></span><br><span class="line">router.push(&#123; <span class="attr">name</span>: <span class="string">&#x27;user&#x27;</span>, <span class="attr">params</span>: &#123; userId &#125;&#125;) <span class="comment">// -&gt; /user/123</span></span><br><span class="line">router.push(&#123; <span class="attr">path</span>: <span class="string">`/user/<span class="subst">$&#123;userId&#125;</span>`</span> &#125;) <span class="comment">// -&gt; /user/123</span></span><br><span class="line"><span class="comment">// 这里的 params 不生效</span></span><br><span class="line">router.push(&#123; <span class="attr">path</span>: <span class="string">&#x27;/user&#x27;</span>, <span class="attr">params</span>: &#123; userId &#125;&#125;) <span class="comment">// -&gt; /user</span></span><br></pre></td></tr></table></figure>

<p><strong>注意：如果提供了 <code>path</code>，<code>params</code> 会被忽略，params将以path里面的为准</strong></p>
<p>router.replace()类似于push，只是替换掉history里面的当前记录</p>
<p>router.go(n)这个方法的参数是一个整数，意思是在 history 记录中向前或者后退多少步</p>
<h4 id="命名路由"><a href="#命名路由" class="headerlink" title="命名路由"></a><strong>命名路由</strong></h4><p>通过一个名称来标识一个路由</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> VueRouter(&#123;</span><br><span class="line">  <span class="attr">routes</span>: [</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="attr">path</span>: <span class="string">&#x27;/user/:userId&#x27;</span>,</span><br><span class="line">      <span class="attr">name</span>: <span class="string">&#x27;user&#x27;</span>,</span><br><span class="line">      <span class="attr">component</span>: User</span><br><span class="line">    &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">&lt;router-link :to=<span class="string">&quot;&#123; name: &#x27;user&#x27;, params: &#123; userId: 123 &#125;&#125;&quot;</span>&gt;User&lt;/router-link&gt;</span><br><span class="line"><span class="comment">//这跟代码调用 router.push() 是一回事：</span></span><br><span class="line">router.push(&#123; <span class="attr">name</span>: <span class="string">&#x27;user&#x27;</span>, <span class="attr">params</span>: &#123; <span class="attr">userId</span>: <span class="number">123</span> &#125;&#125;)</span><br></pre></td></tr></table></figure>

<p><strong>命名视图</strong></p>
<p>同时 (同级) 展示多个视图，而不是嵌套展示，你可以在界面中拥有多个单独命名的视图，而不是只有一个单独的出口。之前router-link时，只有一个router-view进行替换，只会有一个视图，现在可通过命名视图将几个视图合在一个页面上。</p>
<p>一个视图使用一个组件渲染，因此对于同个路由，多个视图就需要多个组件。需要使用components进行配置，默认为default。也可配合嵌套路由，在childern里面使用命名视图。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">&lt;router-view <span class="class"><span class="keyword">class</span></span>=<span class="string">&quot;view one&quot;</span>&gt;&lt;/router-view&gt;</span><br><span class="line"><span class="xml"><span class="tag">&lt;<span class="name">router-view</span> <span class="attr">class</span>=<span class="string">&quot;view two&quot;</span> <span class="attr">name</span>=<span class="string">&quot;a&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">router-view</span>&gt;</span></span></span><br><span class="line"><span class="xml"><span class="tag">&lt;<span class="name">router-view</span> <span class="attr">class</span>=<span class="string">&quot;view three&quot;</span> <span class="attr">name</span>=<span class="string">&quot;b&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">router-view</span>&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> VueRouter(&#123;</span><br><span class="line">  <span class="attr">routes</span>: [</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="attr">path</span>: <span class="string">&#x27;/&#x27;</span>,</span><br><span class="line">      <span class="attr">components</span>: &#123;</span><br><span class="line">        <span class="attr">default</span>: Foo,</span><br><span class="line">        <span class="attr">a</span>: Bar,</span><br><span class="line">        <span class="attr">b</span>: Baz</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h4 id="重定向和别名"><a href="#重定向和别名" class="headerlink" title="重定向和别名"></a><strong>重定向和别名</strong></h4><figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> VueRouter(&#123;</span><br><span class="line">  <span class="attr">routes</span>: [</span><br><span class="line">    &#123; <span class="attr">path</span>: <span class="string">&#x27;/a&#x27;</span>, <span class="attr">redirect</span>: <span class="string">&#x27;/b&#x27;</span> &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;)</span><br><span class="line">重定向的目标也可以是一个命名的路由：</span><br><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> VueRouter(&#123;</span><br><span class="line">  <span class="attr">routes</span>: [</span><br><span class="line">    &#123; <span class="attr">path</span>: <span class="string">&#x27;/a&#x27;</span>, <span class="attr">redirect</span>: &#123; <span class="attr">name</span>: <span class="string">&#x27;foo&#x27;</span> &#125;&#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;)</span><br><span class="line">甚至是一个方法，动态返回重定向目标：</span><br><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> VueRouter(&#123;</span><br><span class="line">  <span class="attr">routes</span>: [</span><br><span class="line">    &#123; <span class="attr">path</span>: <span class="string">&#x27;/a&#x27;</span>, <span class="attr">redirect</span>: <span class="function"><span class="params">to</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="comment">// 方法接收 目标路由 作为参数</span></span><br><span class="line">      <span class="comment">// return 重定向的 字符串路径/路径对象</span></span><br><span class="line">    &#125;&#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>​    <code>    /a</code> 的别名是 <code>/b</code>，意味着，当用户访问 <code>/b</code> 时，URL 会保持为 <code>/b</code>，但是路由匹配则为 <code>/a</code>，就像用户访问 <code>/a</code> 一样。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> VueRouter(&#123;</span><br><span class="line">  <span class="attr">routes</span>: [</span><br><span class="line">    &#123; <span class="attr">path</span>: <span class="string">&#x27;/a&#x27;</span>, <span class="attr">component</span>: A, <span class="attr">alias</span>: <span class="string">&#x27;/b&#x27;</span> &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>“别名”的功能让你可以自由地将 UI 结构映射到任意的 URL，而不是受限于配置的嵌套路由结构。</p>
<h4 id="路由组件传参"><a href="#路由组件传参" class="headerlink" title="路由组件传参"></a><strong>路由组件传参</strong></h4><p>在组件中使用 <code>$route</code> 会使之与其对应路由形成高度耦合，从而使组件只能在某些特定的 URL 上使用，限制了其灵活性。使用 <code>props</code> 将组件和路由解耦：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> User = &#123;</span><br><span class="line">  <span class="attr">template</span>: <span class="string">&#x27;&lt;div&gt;User &#123;&#123; $route.params.id &#125;&#125;&lt;/div&gt;&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> VueRouter(&#123;</span><br><span class="line">  <span class="attr">routes</span>: [</span><br><span class="line">    &#123; <span class="attr">path</span>: <span class="string">&#x27;/user/:id&#x27;</span>, <span class="attr">component</span>: User &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">//组件传参props</span></span><br><span class="line"><span class="keyword">const</span> User = &#123;</span><br><span class="line">  <span class="attr">props</span>: [<span class="string">&#x27;id&#x27;</span>],</span><br><span class="line">  <span class="attr">template</span>: <span class="string">&#x27;&lt;div&gt;User &#123;&#123; id &#125;&#125;&lt;/div&gt;&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> VueRouter(&#123;</span><br><span class="line">  <span class="attr">routes</span>: [</span><br><span class="line">    &#123; <span class="attr">path</span>: <span class="string">&#x27;/user/:id&#x27;</span>, <span class="attr">component</span>: User, <span class="attr">props</span>: <span class="literal">true</span> &#125;,</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 对于包含命名视图的路由，你必须分别为每个命名视图添加 `props` 选项：</span></span><br><span class="line">    &#123;</span><br><span class="line">      <span class="attr">path</span>: <span class="string">&#x27;/user/:id&#x27;</span>,</span><br><span class="line">      <span class="attr">components</span>: &#123; <span class="attr">default</span>: User, <span class="attr">sidebar</span>: Sidebar &#125;,</span><br><span class="line">      <span class="attr">props</span>: &#123; <span class="attr">default</span>: <span class="literal">true</span>, <span class="attr">sidebar</span>: <span class="literal">false</span> &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>在组件里也使用props将传入的数据拿到，进行数据显示。</p>
<h4 id="路由守卫"><a href="#路由守卫" class="headerlink" title="路由守卫"></a><strong>路由守卫</strong></h4><p>简单来说就是路由在跳转之前的验证，当满足条件时才会进行跳转。分为<code>全局守卫</code>，<code>路由守卫</code>和<code>组件守卫</code></p>
<p>1.注册全局守卫应该在路由模块暴露出去之前定义，所有的路由跳转都会被调用使用<code>router.beforeEach(function(to,from,next)&#123;&#125;)</code>来注册一个全局守卫。</p>
<p>参数：</p>
<ul>
<li><p>to：代表目标路径对象</p>
</li>
<li><p>from：来源路径对象</p>
</li>
<li><p>next：用于决定是否继续进行跳转。</p>
<p>当next()函数不传参数或者传入true的时候 则允许正常跳转；</p>
<p>当next()函数传入false时 会中断跳转(阻止跳转)；</p>
<p>当next()函数中<strong>传入路径</strong>时或者<strong>对象</strong>时(比如:{name:’xxx’})则会重定向到指定路径。</p>
</li>
</ul>
<p>2.路由守卫就是针对单个路由对象配置的守卫。<strong>beforeEnter</strong></p>
<p>假如我在users组件配置路由守卫，那么只有跳转到users路由时才会触发该守卫，跳转到其他路由时不会触发该守卫。</p>
<p>路由守卫的注册写在路由匹配规则数组里面：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> router = <span class="keyword">new</span> Router(&#123;    </span><br><span class="line">    <span class="attr">routes</span>: [        <span class="comment">//...        </span></span><br><span class="line">    &#123;<span class="attr">path</span>: <span class="string">&#x27;/users&#x27;</span>,            </span><br><span class="line">     <span class="attr">component</span>: Users,            </span><br><span class="line">     <span class="attr">name</span>: <span class="string">&#x27;u&#x27;</span>,            </span><br><span class="line">     <span class="attr">beforeEnter</span>: <span class="function">(<span class="params">to, <span class="keyword">from</span>, next</span>) =&gt;</span> &#123;                					</span><br><span class="line">         next(confirm(<span class="string">&#x27;Entey Users?&#x27;</span>));           </span><br><span class="line">&#125;&#125;]&#125;);</span><br></pre></td></tr></table></figure>

<p>3.组件守卫是针对单个组件进行监听，在访问到该组件时才会触发。</p>
<p>写在组件里</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">let</span> Home = &#123;</span><br><span class="line">    <span class="attr">template</span>: <span class="string">`</span></span><br><span class="line"><span class="string">        &lt;div&gt;</span></span><br><span class="line"><span class="string">            &lt;h1&gt;首页&lt;/h1&gt;</span></span><br><span class="line"><span class="string">            &lt;router-view&gt;&lt;/router-view&gt;</span></span><br><span class="line"><span class="string">            &lt;router-view name=&quot;b&quot;&gt;&lt;/router-view&gt;</span></span><br><span class="line"><span class="string">        &lt;/div&gt;</span></span><br><span class="line"><span class="string">    `</span>,</span><br><span class="line">    beforeRouteEnter (to, <span class="keyword">from</span>, next) &#123;</span><br><span class="line">    <span class="comment">// 在渲染该组件的对应路由被 confirm 前调用</span></span><br><span class="line">    <span class="comment">// 不！能！获取组件实例 `this`</span></span><br><span class="line">    <span class="comment">// 因为当守卫执行前，组件实例还没被创建</span></span><br><span class="line">   &#125;,</span><br><span class="line">   beforeRouteUpdate (to, <span class="keyword">from</span>, next) &#123;</span><br><span class="line">    <span class="comment">// 在当前路由改变，但是该组件被复用时调用</span></span><br><span class="line">    <span class="comment">// 举例来说，对于一个带有动态参数的路径 /foo/:id，在 /foo/1 和 /foo/2 之间跳转的时候，</span></span><br><span class="line">    <span class="comment">// 由于会渲染同样的 Foo 组件，因此组件实例会被复用。而这个钩子就会在这个情况下被调用。</span></span><br><span class="line">    <span class="comment">// 可以访问组件实例 `this`</span></span><br><span class="line">   &#125;,</span><br><span class="line">   beforeRouteLeave (to, <span class="keyword">from</span>, next) &#123;</span><br><span class="line">    <span class="comment">// 导航离开该组件的对应路由时调用</span></span><br><span class="line">    <span class="comment">// 可以访问组件实例 `this`</span></span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h4 id="完整的导航解析流程"><a href="#完整的导航解析流程" class="headerlink" title="完整的导航解析流程"></a>完整的导航解析流程</h4><ol>
<li><p>导航被触发。</p>
</li>
<li><p>在失活的组件里调用 <code>beforeRouteLeave</code> 守卫。</p>
</li>
<li><p>调用全局的 <code>beforeEach</code> 守卫。</p>
</li>
<li><p>在重用的组件里调用 <code>beforeRouteUpdate</code> 守卫 (2.2+)。</p>
</li>
<li><p>在路由配置里调用 <code>beforeEnter</code>。</p>
</li>
<li><p>解析异步路由组件。</p>
</li>
<li><p>在被激活的组件里调用 <code>beforeRouteEnter</code>。</p>
</li>
<li><p>调用全局的 <code>beforeResolve</code> 守卫 (2.5+)。</p>
</li>
<li><p>导航被确认。</p>
</li>
<li><p>调用全局的 <code>afterEach</code> 钩子。</p>
</li>
<li><p>触发 DOM 更新。</p>
</li>
<li><p>调用 <code>beforeRouteEnter</code> 守卫中传给 <code>next</code> 的回调函数，创建好的组件实例会作为回调函数的参数传入。</p>
<hr>
</li>
</ol>
<h4 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h4><h5 id="路由元信息"><a href="#路由元信息" class="headerlink" title="路由元信息"></a><strong>路由元信息</strong></h5><p>路由的特有属性，写在meta:{ }里面，为后面的组件提供一些特定信息进行逻辑判断。</p>
<p>一个路由匹配到的所有路由记录会暴露为 <code>$route</code> 对象 (还有在导航守卫中的路由对象) 的 <code>$route.matched</code> 数组。因此，我们需要遍历 <code>$route.matched</code> 来检查路由记录中的 <code>meta</code> 字段。</p>
<h5 id="过渡动效"><a href="#过渡动效" class="headerlink" title="过渡动效"></a><strong>过渡动效</strong></h5><p>用 <code>&lt;transition&gt;</code> 组件给它添加一些过渡效果</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">&lt;transition name=<span class="string">&quot;slide&quot;</span> mode=<span class="string">&quot;out-in&quot;</span> </span><br><span class="line">enter-active-<span class="class"><span class="keyword">class</span></span>=<span class="string">&quot;animated bounceInLeft&quot;</span> </span><br><span class="line">leave-active-<span class="class"><span class="keyword">class</span></span>=<span class="string">&quot;animated bounceOutRight&quot;</span>&gt;</span><br><span class="line">      <span class="xml"><span class="tag">&lt;<span class="name">keep-alive</span>&gt;</span></span></span><br><span class="line"><span class="xml">        <span class="tag">&lt;<span class="name">router-view</span>/&gt;</span></span></span><br><span class="line"><span class="xml">      <span class="tag">&lt;/<span class="name">keep-alive</span>&gt;</span></span></span><br><span class="line">      </span><br><span class="line">    &lt;/transition&gt;</span><br></pre></td></tr></table></figure>

<h5 id="数据获取"><a href="#数据获取" class="headerlink" title="数据获取"></a><strong>数据获取</strong></h5><p>我们可以通过两种方式来实现：</p>
<ul>
<li><strong>导航完成之后获取</strong>：先完成导航，然后在接下来的组件生命周期created钩子中获取数据。在数据获取期间显示“加载中”之类的指示。</li>
<li><strong>导航完成之前获取</strong>：导航完成前，在路由进入的守卫中获取数据，在数据获取成功后执行导航。在为后面的视图获取数据时，用户会停留在当前的界面，因此建议在数据获取期间，显示一些进度条或者别的指示。如果数据获取失败，同样有必要展示一些全局的错误提醒。</li>
</ul>
<p>从技术角度讲，两种方式都不错 —— 就看你想要的用户体验是哪种。</p>
<h5 id="滚动行为"><a href="#滚动行为" class="headerlink" title="滚动行为"></a><strong>滚动行为</strong></h5><p>使用前端路由，当切换到新路由时，想要页面滚到顶部，或者是保持原先的滚动位置，就像重新加载页面那样。 <code>vue-router</code> 能做到，而且更好，它让你可以自定义路由切换时页面如何滚动。</p>
<p>当创建一个 Router 实例，你可以提供一个 <code>scrollBehavior</code> 方法</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">scrollBehavior (to, <span class="keyword">from</span>, savedPosition) &#123;</span><br><span class="line">  <span class="keyword">if</span> (savedPosition) &#123;</span><br><span class="line">    <span class="keyword">return</span> savedPosition</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> &#123; <span class="attr">x</span>: <span class="number">0</span>, <span class="attr">y</span>: <span class="number">0</span> &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="路由懒加载"><a href="#路由懒加载" class="headerlink" title="路由懒加载"></a><strong>路由懒加载</strong></h5><p>当打包构建应用时，JavaScript 包会变得非常大，影响页面加载。如果我们能把不同路由对应的组件分割成不同的代码块，然后当路由被访问的时候才加载对应组件，这样就更加高效了</p>
</div></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">晟松</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://chengsong.info/2020/07/15/vue-router/">https://chengsong.info/2020/07/15/vue-router/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://chengsong.info">晟松</a>！</span></div></div><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/vue-less-route/">vue less route</a></div><nav id="pagination"><div class="prev-post pull-left"><a href="/2020/07/19/vue-vuex/"><i class="fa fa-chevron-left">  </i><span>vue-vuex</span></a></div><div class="next-post pull-right"><a href="/2020/07/13/vue%E8%BF%9B%E4%B8%80%E6%AD%A5%E5%AD%A6%E4%B9%A0/"><span>vue进一步学习</span><i class="fa fa-chevron-right"></i></a></div></nav></div></div><footer class="footer-bg" style="background-image: url(/img/blog-bg.jpg)"><div class="layout" id="footer"><div class="copyright">&copy;2020 - 2023 By 晟松</div><div class="framework-info"><span>驱动 - </span><a target="_blank" rel="noopener" href="http://hexo.io"><span>Hexo</span></a><span class="footer-separator">|</span><span>主题 - </span><a target="_blank" rel="noopener" href="https://github.com/Molunerfinn/hexo-theme-melody"><span>Melody</span></a></div><div class="icp"><a target="_blank" rel="noopener" href="http://www.beian.miit.gov.cn/"><span>湘ICP备2020021729号</span></a></div><div class="busuanzi"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span id="busuanzi_container_page_pv"><i class="fa fa-file"></i><span id="busuanzi_value_page_pv"></span><span></span></span></div></div></footer><i class="fa fa-arrow-up" id="go-up" aria-hidden="true"></i><script src="https://cdn.jsdelivr.net/npm/animejs@latest/anime.min.js"></script><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@latest/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-ui-pack@latest/velocity.ui.min.js"></script><script src="/js/utils.js?version=1.9.0"></script><script src="/js/fancybox.js?version=1.9.0"></script><script src="/js/sidebar.js?version=1.9.0"></script><script src="/js/copy.js?version=1.9.0"></script><script src="/js/fireworks.js?version=1.9.0"></script><script src="/js/transition.js?version=1.9.0"></script><script src="/js/scroll.js?version=1.9.0"></script><script src="/js/head.js?version=1.9.0"></script><script src="/js/search/local-search.js"></script><script>if(/Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent)) {
  $('#nav').addClass('is-mobile')
  $('footer').addClass('is-mobile')
  $('#top-container').addClass('is-mobile')
}</script><div class="search-dialog" id="local-search"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章"></div></div></div><hr><div id="local-search-results"><div id="local-hits"></div><div id="local-stats"><div class="local-search-stats__hr" id="hr"><span>由</span> <a target="_blank" rel="noopener" href="https://github.com/wzpan/hexo-generator-search" style="color:#49B1F5;">hexo-generator-search</a>
 <span>提供支持</span></div></div></div><span class="search-close-button"><i class="fa fa-times"></i></span></div><div class="search-mask"></div></body></html>